<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2022-06-05
 * Time: 16:32
 */

namespace app\services;


use app\models\OrderExpress;
use app\models\OrderGoods;
use app\models\Orders;
use GuzzleHttp\Client;

class OrderService extends ServiceBase
{
    /**
     * @param $params
     * @param int $page
     * @param int $limit
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getLists($params, $page = 1, $limit = 10)
    {
        $orders = Orders::lists($params, $page, $limit);

        return $orders;
    }
    /**
     * @param $orderId
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderDetail($orderId)
    {
        $order = Orders::find($orderId);

        return $order;
    }

    /**
     * @param $orderNo
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDetailByOrderNo($orderNo)
    {
        $order = Orders::where(['orderNo' => $orderNo])->find();

        return $order;
    }

    /**
     * @param $orderId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGoods($orderId)
    {
        $goods = OrderGoods::where(['orderId' => $orderId])->select();

        $data = [];
        if ($goods) {
            foreach ($goods as $good) {
                $data[] = [
                    'orderGoodsId'=>$good->orderGoodsId,
                    'goodsId' => $good->goodsId,
                    'goodsName' => $good->goods->goodsName,
                    'goodsCategoryId' => $good->goodsCategoryId,
                    'goodsNum' => $good->goodsNums,
                    'thumb' => $good->goods->thumb,
                    'marketPrice' => $good->goods->marketPrice,
                    'credit' => $good->credit,
                ];
            }
        }
        $datas['data']  = $data;
        return $datas;
    }

    /**
     * 订单撤单
     * @param $orderId
     * @return bool
     * @throws \Exception
     */
    public function cancel(Orders $order)
    {
        try {
            $order->orderStatus = -1;
            $order->save();

            foreach ($order->orderGoods as $good) {
                (new GoodsService())->addStock($good->goods, $good->goodsNum);

                $remark = '撤销兑换'.$good->goodsName;
                (new UserCreditService)->add($order->user, $good->credit, $remark);
            }

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * 生成预付订单
     * @param $good
     * @param $goodsNum
     * @return mixed
     */
    public function getPreviewOrder($good, $goodsNum)
    {
        $data = [
            'goodsId' => $good->goodsId,
            'goodsName' => $good->goodsName,
            'goodsCategoryId' => $good->categoryId,
            'thumb' => $good->thumb,
            'marketPrice' => $good->marketPrice,
            'credit' => $good->credit,
            'stock' => $good->stock,
            'models' => $good->getModels()
        ];

        $totalAmount = bcmul($good->credit, $goodsNum);


        $return['goods'] = $data;
        $return['goodsNum'] = $goodsNum;
        $return['totalCredit'] = $totalAmount;

        return $return;
    }

    /**
     * @param $carts
     * @param $address
     * @param $user
     * @return mixed|string
     */
    public function create($previewData, $address, $user, $appletId, $consign)
    {
        $orderNo = (new UtilService())->getOrderNo($user->userId);

        $order = new Orders();
        $order->appletId = $appletId;
        $order->orderNo = $orderNo;
        $order->userId = $user->userId;
        $order->userName = $user->userName;
        $order->totalCredit = $previewData['totalCredit'];
        $order->orderStatus = 1;
        $order->save();

        $orderGoods = new OrderGoods();
        $orderGoods->orderId = $order->orderId;
        $orderGoods->goodsId = $previewData['goods']['goodsId'];
        $orderGoods->goodsName = $previewData['goods']['goodsName'];
        $orderGoods->goodsCategoryId = $previewData['goods']['goodsCategoryId'];
        $orderGoods->goodsNums = $previewData['goodsNum'];
        $orderGoods->credit = $previewData['goods']['credit'];
        $orderGoods->save();

        $orderExpress = new OrderExpress();
        $orderExpress->orderId = $order->orderId;
        $orderExpress->categoryId = $orderGoods->goodsCategoryId;
        if ($orderGoods->goodsCategoryId == 2 && $address) {
            $orderExpress->provinceCode = $address->provinceCode;
            $orderExpress->cityCode = $address->cityCode;
            $orderExpress->areaCode = $address->areaCode;
            $orderExpress->consignee = $address->consignee;
            $orderExpress->address = $address->address;
            $orderExpress->phone = $address->phone;
            $orderExpress->expressStatus = 0;
            $orderExpress->save();
        }

        if (count($consign) > 0) {
            foreach ($consign as $key => $val) {
                $orderExpress->$key = $val;
            }
            $orderExpress->save();
        }

        return [
            'orderNo' => $order->orderNo
        ];
    }

    /**
     * 订单发货
     * @param $orderId
     * @param $params
     * @throws \Exception
     */
    public function express(Orders $order, $params)
    {
        try {
            $express = OrderExpress::where(['orderId' => $order->orderId])->find();

            if ($express) {
                $express->adminId = $params['adminId'];
                $express->expressCompany = $params['expressCompany'];
                $express->expressNo = $params['expressNo'];
                $express->expressAt = date('Y-m-d H:i:s');
                $express->expressStatus = 1;
                $express->save();
            }

            $order->orderStatus = 2;
            $order->save();

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    public function synQuery($order)
    {
        $key = 'GIvzNwwW2387';                        //客户授权key
        $customer = '36E656E792AD92D8579A633183F9431E';                   //查询公司编号
        $param = array (
            'com' => $order->express->expressCode,             //快递公司编码
            'num' => $order->express->expressNo,    //快递单号
            'resultv2' => '1'             //开启行政区域解析
        );

        //请求参数
        $postData = [
            'form_params' =>[
                "customer" => $customer,
                "param" => json_encode($param),
                "sign" => strtoupper(md5(json_encode($param).$key.$customer))
            ]
        ];

        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址



        $res = (new Client())->post($url, $postData);

        $data = json_decode($res->getBody()->__toString());

        if ($data->status != 200) {
            throw new \Exception('数据查找不到', 500);
        }

        return $data->data;
    }

    public function export($select)
    {
        $title = '中益订单'.date('YmdHis');

        $orders = Orders::where($select['where'])
            ->order($select['order'])
            ->select();

        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel); //设置保存版本格式

        $objPHPExcel->getActiveSheet()->setCellValue('A1', 'ID');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '订单号');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '商品名');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '用户唯一码');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '用户姓名');
        $objPHPExcel->getActiveSheet()->setCellValue('F1', '联系电话');
        $objPHPExcel->getActiveSheet()->setCellValue('G1', '志愿者编号');
        $objPHPExcel->getActiveSheet()->setCellValue('H1', '邮箱');
        $objPHPExcel->getActiveSheet()->setCellValue('I1', '订单状态');
        $objPHPExcel->getActiveSheet()->setCellValue('J1', '下单时间');

        foreach ($orders as $key => $order) {
            $i = $key + 2;
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $order->orderId,\PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $order->orderNo,\PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $order->orderGoods[0]->goodsName,\PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $order->user->uniCode,\PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $order->express()->value('consignee'),\PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $order->express()->value('phone'),\PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $order->express()->value('number').' ',\PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $order->express()->value('email'),\PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $order->getOrderStatusText(),\PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValue('J' . $i, $order->createdAt,\PHPExcel_Cell_DataType::TYPE_STRING);
        }

        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename='.$title.'.xlsx');
        header("Content-Transfer-Encoding:binary");
//        $objWriter->save($title.'.xls');
        $objWriter->save('php://output');
    }
}